﻿#include <QDebug>
#include <QMutex>
#include <QTimer>
#include <thread>
#include "Qffplayer.h"
#include <QEventLoop>
#include <iostream>
#include <thread>
#include <sstream>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

QImage pic_handle(AVFrame* img, int format);
QImage add_mask(AVFrame* img, int format, QString mask, int x, int y);
QImage set_amusingMirror1(AVFrame* img, int format);
QImage set_cv_mosic(AVFrame* frame, int format, int x, int y, int width, int height);

#pragma execution_character_set("utf-8")

//数据包队列存放数据包（供队列内部使用）
static int packet_queue_put_private(PacketQueue *q, AVPacket *pkt)
{
    MyAVPacketList pkt1;
    int ret;

    if (q->abort_request)
        return -1;


    pkt1.pkt = pkt;
    pkt1.serial = q->serial;

    ret = av_fifo_write(q->pkt_list, &pkt1, 1);
    if (ret < 0)
        return ret;
    q->nb_packets++;
    q->size += pkt1.pkt->size + sizeof(pkt1);
    q->duration += pkt1.pkt->duration;
    /* XXX: should duplicate packet data in DV case */
    SDL_CondSignal(q->cond);
    return 0;
}

//数据包队列存放数据包
static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
{
    AVPacket* pkt1;
    int ret;

    pkt1 = av_packet_alloc();
    if (!pkt1) {
        av_packet_unref(pkt);
        return -1;
    }
    av_packet_move_ref(pkt1, pkt);

    SDL_LockMutex(q->mutex);
    ret = packet_queue_put_private(q, pkt1);
    SDL_UnlockMutex(q->mutex);

    if (ret < 0)
        av_packet_free(&pkt1);

    return ret;
}

//数据包队列存放空数据包
static int packet_queue_put_nullpacket(PacketQueue* q, AVPacket* pkt, int stream_index)
{
    pkt->stream_index = stream_index;
    return packet_queue_put(q, pkt);
}

/* packet queue handling */
//数据包队列初始化
static int packet_queue_init(PacketQueue *q)
{
    memset(q, 0, sizeof(PacketQueue));
    q->pkt_list = av_fifo_alloc2(1, sizeof(MyAVPacketList), AV_FIFO_FLAG_AUTO_GROW);
    if (!q->pkt_list)
        return AVERROR(ENOMEM);
    q->mutex = SDL_CreateMutex();
    if (!q->mutex) {
        av_log(NULL, AV_LOG_FATAL, "SDL_CreateMutex(): %s\n", SDL_GetError());
        return AVERROR(ENOMEM);
    }
    q->cond = SDL_CreateCond();
    if (!q->cond) {
        av_log(NULL, AV_LOG_FATAL, "SDL_CreateCond(): %s\n", SDL_GetError());
        return AVERROR(ENOMEM);
    }
    q->abort_request = 1;
    return 0;
}
//数据包队列清空
static void packet_queue_flush(PacketQueue *q)
{
    MyAVPacketList pkt1;

    SDL_LockMutex(q->mutex);
    while (av_fifo_read(q->pkt_list, &pkt1, 1) >= 0)
        av_packet_free(&pkt1.pkt);
    q->nb_packets = 0;
    q->size = 0;
    q->duration = 0;
    q->serial++;
    SDL_UnlockMutex(q->mutex);
}
//数据包队列销毁
static void packet_queue_destroy(PacketQueue *q)
{
    packet_queue_flush(q);
    av_fifo_freep2(&q->pkt_list);
    SDL_DestroyMutex(q->mutex);
    SDL_DestroyCond(q->cond);
}
//数据包队列停用
static void packet_queue_abort(PacketQueue *q)
{
    SDL_LockMutex(q->mutex);

    q->abort_request = 1;

    SDL_CondSignal(q->cond);

    SDL_UnlockMutex(q->mutex);
}
//数据包队列开始使用
static void packet_queue_start(PacketQueue *q)
{
    SDL_LockMutex(q->mutex);
    q->abort_request = 0;
    q->serial++;
    SDL_UnlockMutex(q->mutex);
}

/* return < 0 if aborted, 0 if no packet and > 0 if packet.  */
//从数据包队列中获取数据包
static int packet_queue_get(PacketQueue* q, AVPacket* pkt, int block, int* serial)
{
    MyAVPacketList pkt1;
    int ret;

    SDL_LockMutex(q->mutex);

    for (;;) {
        if (q->abort_request) {
            ret = -1;
            break;
        }

        if (av_fifo_read(q->pkt_list, &pkt1, 1) >= 0) {
            q->nb_packets--;
            q->size -= pkt1.pkt->size + sizeof(pkt1);
            q->duration -= pkt1.pkt->duration;
            av_packet_move_ref(pkt, pkt1.pkt);
            if (serial)
                *serial = pkt1.serial;
            av_packet_free(&pkt1.pkt);
            ret = 1;
            break;
        }
        else if (!block) {
            ret = 0;
            break;
        }
        else {
            SDL_CondWait(q->cond, q->mutex);
        }
    }
    SDL_UnlockMutex(q->mutex);
    return ret;
}

//解码器初始化（绑定解码结构体、数据包队列、信号量，初始化pts）
static int decoder_init(Decoder* d, AVCodecContext* avctx, PacketQueue* queue, SDL_cond* empty_queue_cond) {
    memset(d, 0, sizeof(Decoder));
    d->pkt = av_packet_alloc();
    if (!d->pkt)
        return AVERROR(ENOMEM);
    d->avctx = avctx;
    d->queue = queue;
    d->empty_queue_cond = empty_queue_cond;
    d->start_pts = AV_NOPTS_VALUE;
    d->pkt_serial = -1;
    return 0;
}

static int writePacket(AVPacket* packet, AVFormatContext* outputContext, int index)
{
    auto outputStream = outputContext->streams[index];
    if(packet->stream_index == 0)
    qDebug() << "track2:" << packet->stream_index<< "pts:" << packet->pts*av_q2d(outputStream->time_base)<< endl;
    return av_interleaved_write_frame(outputContext, packet);
}

//解码一帧数据
int Qffplayer::decoder_decode_frame(Decoder *d, AVFrame *frame, AVSubtitle *sub,  AVPacket** audio_pkt) {
    int decoder_reorder_pts = -1;
    int ret = AVERROR(EAGAIN);
    for (;;) {
        if (d->queue->serial == d->pkt_serial) {
            do {
                if (d->queue->abort_request)
                    return -1;

                switch (d->avctx->codec_type) {
                case AVMEDIA_TYPE_VIDEO:
                    ret = avcodec_receive_frame(d->avctx, frame);
                    if (ret >= 0) {
                        if (decoder_reorder_pts == -1) {
                            frame->pts = frame->best_effort_timestamp;
                        }
                        else if (!decoder_reorder_pts) {
                            frame->pts = frame->pkt_dts;
                        }
                    }
                    break;
                case AVMEDIA_TYPE_AUDIO:
                    ret = avcodec_receive_frame(d->avctx, frame);
                    if (ret >= 0) {
                        AVRational tb = { 1, frame->sample_rate };
                        if (frame->pts != AV_NOPTS_VALUE)
                            frame->pts = av_rescale_q(frame->pts, d->avctx->pkt_timebase, tb);
                        else if (d->next_pts != AV_NOPTS_VALUE)
                            frame->pts = av_rescale_q(d->next_pts, d->next_pts_tb, tb);
                        if (frame->pts != AV_NOPTS_VALUE) {
                            d->next_pts = frame->pts + frame->nb_samples;
                            d->next_pts_tb = tb;
                        }
                    }
                    break;
                }
                if (ret == AVERROR_EOF) {
                    d->finished = d->pkt_serial;
                    avcodec_flush_buffers(d->avctx);
                    return 0;
                }
                if (ret >= 0){
                    return 1;
                }
            } while (ret != AVERROR(EAGAIN));
        }

        do {
            if (d->queue->nb_packets == 0)
                SDL_CondSignal(d->empty_queue_cond);
            if (d->packet_pending) {
                d->packet_pending = 0;
            }
            else {
                int old_serial = d->pkt_serial;
                if (packet_queue_get(d->queue, d->pkt, 1, &d->pkt_serial) < 0)
                    return -1;
                if (old_serial != d->pkt_serial) {
                    avcodec_flush_buffers(d->avctx);
                    d->finished = 0;
                    d->next_pts = d->start_pts;
                    d->next_pts_tb = d->start_pts_tb;
                }
            }
            if (d->queue->serial == d->pkt_serial)
                break;

            av_packet_unref(d->pkt);
        } while (1);

        if (d->avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
            int got_frame = 0;
            ret = avcodec_decode_subtitle2(d->avctx, sub, &got_frame, d->pkt);
            if (ret < 0) {
                ret = AVERROR(EAGAIN);
            }
            else {
                if (got_frame && !d->pkt->data) {
                    d->packet_pending = 1;
                }
                ret = got_frame ? 0 : (d->pkt->data ? AVERROR(EAGAIN) : AVERROR_EOF);
            }
            av_packet_unref(d->pkt);
        }
        else {

            if(this->m_CurStream->out_ctx && this->m_CurStream->audio_encoder && this->m_CurStream->video_encoder
                && d->avctx->codec_type == AVMEDIA_TYPE_AUDIO) // 如果正在录像
                *audio_pkt = av_packet_clone(d->pkt);

            if (avcodec_send_packet(d->avctx, d->pkt) == AVERROR(EAGAIN)) {
                av_log(d->avctx, AV_LOG_ERROR, "Receive_frame and send_packet both returned EAGAIN, which is an API violation.\n");
                d->packet_pending = 1;
            }
            else {
                av_packet_unref(d->pkt);
            }
        }
    }
}
//解码器销毁
static void decoder_destroy(Decoder *d) {
    av_packet_free(&d->pkt);
    avcodec_close(d->avctx);
    avcodec_free_context(&d->avctx);
}

static void frame_queue_unref_item(Frame *vp)
{
    av_frame_unref(vp->frame);
    avsubtitle_free(&vp->sub);
}
//帧队列初始化（绑定数据包队列，初始化最大值）
static int frame_queue_init(FrameQueue *f, PacketQueue *pktq, int max_size, int keep_last)
{
    int i;
    memset(f, 0, sizeof(FrameQueue));
    if (!(f->mutex = SDL_CreateMutex())) {
        av_log(NULL, AV_LOG_FATAL, "SDL_CreateMutex(): %s\n", SDL_GetError());
        return AVERROR(ENOMEM);
    }
    if (!(f->cond = SDL_CreateCond())) {
        av_log(NULL, AV_LOG_FATAL, "SDL_CreateCond(): %s\n", SDL_GetError());
        return AVERROR(ENOMEM);
    }
    f->pktq = pktq;
    f->max_size = FFMIN(max_size, FRAME_QUEUE_SIZE);
    f->keep_last = !!keep_last;
    for (i = 0; i < f->max_size; i++){
        if (!(f->queue[i].frame = av_frame_alloc()))
            return AVERROR(ENOMEM);
        f->queue[i].pkt = NULL;  // 音频包
    }
    return 0;
}
//帧队列销毁
static void frame_queue_destory(FrameQueue *f)
{
    int i;
    for (i = 0; i < f->max_size; i++) {
        Frame* vp = &f->queue[i];
        frame_queue_unref_item(vp);
        av_frame_free(&vp->frame);
    }
    SDL_DestroyMutex(f->mutex);
    SDL_DestroyCond(f->cond);
}
//帧队列信号
static void frame_queue_signal(FrameQueue *f)
{
    SDL_LockMutex(f->mutex);
    SDL_CondSignal(f->cond);
    SDL_UnlockMutex(f->mutex);
}

static Frame* frame_queue_peek(FrameQueue* f)
{
    return &f->queue[(f->rindex + f->rindex_shown) % f->max_size];
}

static Frame* frame_queue_peek_next(FrameQueue* f)
{
    return &f->queue[(f->rindex + f->rindex_shown + 1) % f->max_size];
}

static Frame* frame_queue_peek_last(FrameQueue* f)
{
    return &f->queue[f->rindex];
}

static Frame* frame_queue_peek_writable(FrameQueue* f)
{
    /* wait until we have space to put a new frame */
    SDL_LockMutex(f->mutex);
    while (f->size >= f->max_size &&
           !f->pktq->abort_request) {
        SDL_CondWait(f->cond, f->mutex);
    }
    SDL_UnlockMutex(f->mutex);

    if (f->pktq->abort_request)
        return NULL;

    return &f->queue[f->windex];
}

static Frame* frame_queue_peek_readable(FrameQueue* f)
{
    /* wait until we have a readable a new frame */
    SDL_LockMutex(f->mutex);
    while (f->size - f->rindex_shown <= 0 &&
           !f->pktq->abort_request) {
        SDL_CondWait(f->cond, f->mutex);
    }
    SDL_UnlockMutex(f->mutex);

    if (f->pktq->abort_request)
        return NULL;

    return &f->queue[(f->rindex + f->rindex_shown) % f->max_size];
}

static void frame_queue_push(FrameQueue* f)
{
    if (++f->windex == f->max_size)
        f->windex = 0;
    SDL_LockMutex(f->mutex);
    f->size++;
    SDL_CondSignal(f->cond);
    SDL_UnlockMutex(f->mutex);
}

static void frame_queue_next(FrameQueue* f)
{
    if (f->keep_last && !f->rindex_shown) {
        f->rindex_shown = 1;
        return;
    }
    frame_queue_unref_item(&f->queue[f->rindex]);
    if (++f->rindex == f->max_size)
        f->rindex = 0;
    SDL_LockMutex(f->mutex);
    f->size--;
    SDL_CondSignal(f->cond);
    SDL_UnlockMutex(f->mutex);
}

/* return the number of undisplayed frames in the queue */
static int frame_queue_nb_remaining(FrameQueue* f)
{
    return f->size - f->rindex_shown;
}

/* return last shown position */
static int64_t frame_queue_last_pos(FrameQueue* f)
{
    Frame* fp = &f->queue[f->rindex];
    if (f->rindex_shown && fp->serial == f->pktq->serial)
        return fp->pos;
    else
        return -1;
}

static void decoder_abort(Decoder* d, FrameQueue* fq)
{
    packet_queue_abort(d->queue);
    frame_queue_signal(fq);
    d->decode_thread.join();
    packet_queue_flush(d->queue);
}

static int framedrop = -1;
static int64_t audio_callback_time;

AVFrame*  qImage2AVframe(QImage image, int format, unsigned char** buffer_yuv)
{
    AVFrame *pframe_yuv = av_frame_alloc();
    int w = image.width();
    int h = image.height();
    int  numbytes_yuv = av_image_get_buffer_size((AVPixelFormat)format, w, h, 1);
    *buffer_yuv = (uint8_t*)av_malloc(numbytes_yuv*sizeof(uint8_t));

    int ret_yuv = av_image_fill_arrays(pframe_yuv->data, pframe_yuv->linesize, *buffer_yuv,
                                       AV_PIX_FMT_YUV420P,w,h,1);
    if (ret_yuv < 0)
    {
        return NULL;
    }

    // 设置源图像的参数
    struct SwsContext *sws_ctx = sws_getContext(
        image.width(), image.height(), AV_PIX_FMT_RGB24,
        image.width(), image.height(), AV_PIX_FMT_YUV420P,
        SWS_BILINEAR, nullptr, nullptr, nullptr
        );

    if (!sws_ctx) {
        return NULL;
    }

    // 获取QImage的位图数据
    uchar *const srcData[1] = { reinterpret_cast<uchar*>(const_cast<QImage*>(&image)->bits()) };
    int srcStride[1] = { image.bytesPerLine() };

    // 转换图像
    sws_scale(sws_ctx, srcData, srcStride, 0, image.height(),
              pframe_yuv->data, pframe_yuv->linesize);

    // 释放转换上下文
    sws_freeContext(sws_ctx);
    return pframe_yuv;

}


AVPacket* encodeVideo(AVFrame* frame, AVCodecContext* encodeContext)
{
    int ret = 0;

    ret = avcodec_send_frame(encodeContext, frame);
    if (ret < 0) {


        char __tmp[1024];
        av_strerror(ret, __tmp, sizeof(__tmp));
        qDebug() <<"ffmpeg error:" <<  __tmp << endl;


        return nullptr;
    }

    AVPacket* packet = new AVPacket;
    av_init_packet(packet);
    ret = avcodec_receive_packet(encodeContext, packet);
    if (ret >= 0){
        return packet;
    }else{
        char __tmp[1024];
        av_strerror(ret, __tmp, sizeof(__tmp));
        qDebug() <<"ffmpeg error:" <<  __tmp << endl;
    }
    av_packet_unref(packet);
    delete packet;
    return nullptr;

}

int Qffplayer::transcode2h264(QImage img)
{
    if(this->m_CurStream->out_ctx == NULL)
        return 0;

    int width = this->m_CurStream->video_st->codecpar->width;
    int height = this->m_CurStream->video_st->codecpar->height;
    unsigned char* buffer;
    AVFrame* yuv = qImage2AVframe(img, this->m_CurStream->video_st->codecpar->format, &buffer);
    if(yuv)
    {
        yuv->format = AV_PIX_FMT_YUV420P;
        yuv->width = width;
        yuv->height = height;
        //yuv->pts = 0.04/av_q2d(m_CurStream->out_ctx->streams[m_CurStream->video_stream]->time_base)*c++;

        if(m_CurStream->out_video_pts == -1)
            m_CurStream->out_video_pts = 0;
        yuv->pts = m_CurStream->out_video_pts;
        m_CurStream->out_video_pts += m_CurStream->video_pts_gap;

        /*  一下两行代码会导致录像文件很大，待优化 */
        yuv->pict_type = AV_PICTURE_TYPE_I;// vp->frame->pict_type;
        yuv->key_frame = 1;//vp->frame->key_frame;
        /* end  */
        AVPacket* pkt = encodeVideo(yuv, this->m_CurStream->video_encoder);
        if(pkt ){
            pkt->stream_index = 0;
            writePacket(pkt, this->m_CurStream->out_ctx, this->m_CurStream->out_v_index);
            av_packet_unref(pkt);
        }

        av_frame_free(&yuv);
        av_free(buffer);
    }

    return 0;
}

//显示视频画面
void Qffplayer::video_image_display(PlayerCore *is)
{
    Frame *vp;
    Frame *sp = NULL;
    vp = frame_queue_peek_last(&is->pictq);

    if (!vp->uploaded) {

        if(this->faceDetect){
            QImage img;
            img = pic_handle(vp->frame, vp->frame->format);
            emit sigDisplay(img.copy(), vp->frame->pts);

        }
        else{


            sws_scale(is->rgb_convert_ctx,
                      (const unsigned char* const*)vp->frame->data,
                      vp->frame->linesize,
                      0,
                      vp->frame->height,
                      is->frame_rgb->data,
                      is->frame_rgb->linesize);

            is->frame_rgb->format =AV_PIX_FMT_RGB24;
            is->frame_rgb->width = vp->frame->width;
            is->frame_rgb->height = vp->frame->height;
            QImage img((uchar*)is->frame_rgb->data[0],vp->frame->width,vp->frame->height,QImage::Format_RGB888);
            emit sigDisplay(img.copy(), vp->frame->pts);
        }

        vp->uploaded = 1;
        vp->flip_v = vp->frame->linesize[0] < 0;

    }
}

//关闭流对应的解码器等
void Qffplayer::stream_component_close(PlayerCore *is, int stream_index)
{
    AVFormatContext *ic = is->ic;
    AVCodecParameters *codecpar;

    if (stream_index < 0 || stream_index >= ic->nb_streams)
        return;
    codecpar = ic->streams[stream_index]->codecpar;

    switch (codecpar->codec_type) {
    case AVMEDIA_TYPE_AUDIO:
        decoder_abort(&is->auddec, &is->sampq);
        SDL_CloseAudio();
        SDL_CloseAudioDevice(this->audio_dev);
        decoder_destroy(&is->auddec);
        swr_free(&is->swr_ctx);
        av_freep(&is->audio_buf1);
        is->audio_buf1_size = 0;
        is->audio_buf = NULL;

        if (is->rdft) {
            av_rdft_end(is->rdft);
            av_freep(&is->rdft_data);
            is->rdft = NULL;
            is->rdft_bits = 0;
        }
        break;
    case AVMEDIA_TYPE_VIDEO:
        decoder_abort(&is->viddec, &is->pictq);
        decoder_destroy(&is->viddec);
        break;
    default:
        break;
    }

    ic->streams[stream_index]->discard = AVDISCARD_ALL;
    switch (codecpar->codec_type) {
    case AVMEDIA_TYPE_AUDIO:
        is->audio_st = NULL;
        is->audio_stream = -1;
        break;
    case AVMEDIA_TYPE_VIDEO:
        is->video_st = NULL;
        is->video_stream = -1;
        break;
    default:
        break;
    }
}

void Qffplayer::close_output()
{
    if(m_CurStream->video_encoder)
    {
        avcodec_close(m_CurStream->video_encoder);
        avcodec_free_context(&m_CurStream->video_encoder);
        m_CurStream->video_encoder = NULL;
    }

    if(m_CurStream->audio_encoder)
    {
        avcodec_close(m_CurStream->audio_encoder);
        avcodec_free_context(&m_CurStream->audio_encoder);
        m_CurStream->audio_encoder = NULL;
    }

    if(m_CurStream->out_ctx != NULL)
    {
        av_write_trailer(m_CurStream->out_ctx);
        avformat_close_input(&m_CurStream->out_ctx);
        avformat_free_context(m_CurStream->out_ctx);
        m_CurStream->out_ctx = NULL;
    }

}

//关闭流
void Qffplayer::stream_close(PlayerCore *is)
{
    /* XXX: use a special url_shutdown call to abort parse cleanly */
    is->abort_request = 1;
    is->read_tid.join();

    /* close each stream */
    if (is->audio_stream >= 0){
        stream_component_close(is, is->audio_stream);
    }
    if (is->video_stream >= 0){
        stream_component_close(is, is->video_stream);
    }

    avformat_close_input(&is->ic);
    avformat_free_context(is->ic);
    packet_queue_destroy(&is->videoq);
    packet_queue_destroy(&is->audioq);

    /* free all pictures */
    frame_queue_destory(&is->pictq);
    frame_queue_destory(&is->sampq);
    SDL_DestroyCond(is->continue_read_thread);
    if(is->rgb_convert_ctx)
    {
        sws_freeContext(is->rgb_convert_ctx);
        is->rgb_convert_ctx = NULL;
    }
    if(is->out_buffer_video)
    {
        av_free(is->out_buffer_video);
        is->out_buffer_video = NULL;
    }

    if(is->frame_rgb != NULL)
        av_frame_free(&is->frame_rgb);

    close_output();

    av_free(is);
    is = nullptr;
}

double Qffplayer::get_clock(Clock *c)
{
    if (*c->queue_serial != c->serial)
        return NAN;
    if (c->paused) {
        return c->pts;
    }
    else {
        double time = av_gettime_relative() / 1000000.0;
        return c->pts_drift + time - (time - c->last_updated) * (1.0 - c->speed);
    }
}

void Qffplayer::set_clock_at(Clock *c, double pts, int serial, double time)
{
    c->pts = pts;
    c->last_updated = time;
    c->pts_drift = c->pts - time;
    c->serial = serial;
}

void Qffplayer::set_clock(Clock *c, double pts, int serial)
{
    double time = av_gettime_relative() / 1000000.0;
    set_clock_at(c, pts, serial, time);
}

void Qffplayer::set_clock_speed(Clock *c, double speed)
{
    set_clock(c, get_clock(c), c->serial);
    c->speed = speed;
}

void Qffplayer::init_clock(Clock *c, int *queue_serial)
{
    c->speed = 1.0;
    c->paused = 0;
    c->queue_serial = queue_serial;
    set_clock(c, NAN, -1);
}

void Qffplayer::sync_clock_to_slave(Clock *c, Clock *slave)
{
    double clock = get_clock(c);
    double slave_clock = get_clock(slave);
    if (!std::isnan(slave_clock) && (std::isnan(clock) || fabs(clock - slave_clock) > AV_NOSYNC_THRESHOLD))
        set_clock(c, slave_clock, slave->serial);
}

int Qffplayer::get_master_sync_type(PlayerCore *is) {
    if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
        if (is->video_st)
            return AV_SYNC_VIDEO_MASTER;
        else
            return AV_SYNC_AUDIO_MASTER;
    }
    else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
        if (is->audio_st)
            return AV_SYNC_AUDIO_MASTER;
        else
            return AV_SYNC_EXTERNAL_CLOCK;
    }
    else {
        return AV_SYNC_EXTERNAL_CLOCK;
    }
}

/* get the current master clock value */
double Qffplayer::get_master_clock(PlayerCore *is)
{
    double val;

    switch (get_master_sync_type(is)) {
    case AV_SYNC_VIDEO_MASTER:
        val = get_clock(&is->vidclk);
        break;
    case AV_SYNC_AUDIO_MASTER:
        val = get_clock(&is->audclk);
        break;
    default:
        val = get_clock(&is->extclk);
        break;
    }
    return val;
}

void Qffplayer::check_external_clock_speed(PlayerCore *is) {
    if (is->video_stream >= 0 && is->videoq.nb_packets <= EXTERNAL_CLOCK_MIN_FRAMES ||
        is->audio_stream >= 0 && is->audioq.nb_packets <= EXTERNAL_CLOCK_MIN_FRAMES) {
        set_clock_speed(&is->extclk, FFMAX(EXTERNAL_CLOCK_SPEED_MIN, is->extclk.speed - EXTERNAL_CLOCK_SPEED_STEP));
    }
    else if ((is->video_stream < 0 || is->videoq.nb_packets > EXTERNAL_CLOCK_MAX_FRAMES) &&
             (is->audio_stream < 0 || is->audioq.nb_packets > EXTERNAL_CLOCK_MAX_FRAMES)) {
        set_clock_speed(&is->extclk, FFMIN(EXTERNAL_CLOCK_SPEED_MAX, is->extclk.speed + EXTERNAL_CLOCK_SPEED_STEP));
    }
    else {
        double speed = is->extclk.speed;
        if (speed != 1.0)
            set_clock_speed(&is->extclk, speed + EXTERNAL_CLOCK_SPEED_STEP * (1.0 - speed) / fabs(1.0 - speed));
    }
}

/* seek in the stream */
void Qffplayer::stream_seek(PlayerCore *is, int64_t pos, int64_t rel)
{
    if (!is->seek_req) {
        is->seek_pos = pos;
        is->seek_rel = rel;
        is->seek_flags &= ~AVSEEK_FLAG_BYTE;
        is->seek_req = 1;
        SDL_CondSignal(is->continue_read_thread);
    }
}

/* pause or resume the video */
void Qffplayer::stream_toggle_pause(PlayerCore *is)
{
    if (is->paused) {
        is->frame_timer += av_gettime_relative() / 1000000.0 - is->vidclk.last_updated;
        if (is->read_pause_return != AVERROR(ENOSYS)) {
            is->vidclk.paused = 0;
        }
        set_clock(&is->vidclk, get_clock(&is->vidclk), is->vidclk.serial);
    }
    set_clock(&is->extclk, get_clock(&is->extclk), is->extclk.serial);
    is->paused = is->audclk.paused = is->vidclk.paused = is->extclk.paused = !is->paused;
}

void Qffplayer::toggle_pause(PlayerCore *is)
{
    stream_toggle_pause(is);
    is->step = 0;
}

int Qffplayer::step_to_next_frame()
{
    if(m_CurStream == NULL || m_CurStream->realtime == 1)
        return -1;
    /* if the stream is paused unpause it, then step */
    if (m_CurStream->paused)
        stream_toggle_pause(m_CurStream);
    m_CurStream->step = 1;

    return 0;
}

double Qffplayer::compute_target_delay(double delay, PlayerCore *is)
{
    double sync_threshold, diff = 0;

    /* update delay to follow master synchronisation source */
    if (get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER) {
        /* if video is slave, we try to correct big delays by
        duplicating or deleting a frame */
        diff = get_clock(&is->vidclk) - get_master_clock(is);

        /* skip or repeat frame. We take into account the
        delay to compute the threshold. I still don't know
        if it is the best guess */
        sync_threshold = FFMAX(AV_SYNC_THRESHOLD_MIN, FFMIN(AV_SYNC_THRESHOLD_MAX, delay));
        if (!std::isnan(diff) && fabs(diff) < is->max_frame_duration) {
            if (diff <= -sync_threshold)
                delay = FFMAX(0, delay + diff);
            else if (diff >= sync_threshold && delay > AV_SYNC_FRAMEDUP_THRESHOLD)
                delay = delay + diff;
            else if (diff >= sync_threshold && m_CurStream->play_speed==1)
                delay = 2 * delay;
        }
    }

    av_log(NULL, AV_LOG_TRACE, "video: delay=%0.3f A-V=%f\n",
           delay, -diff);

    return delay;
}

double Qffplayer::vp_duration(PlayerCore *is, Frame *vp, Frame *nextvp) {
    if (vp->serial == nextvp->serial) {
        double duration = nextvp->pts - vp->pts;
        if (std::isnan(duration) || duration <= 0 || duration > is->max_frame_duration)
            return vp->duration;
        else
            return duration;
    }
    else {
        return 0.0;
    }
}

void Qffplayer::update_video_pts(PlayerCore *is, double pts, int64_t pos, int serial) {
    /* update current video pts */
    set_clock(&is->vidclk, pts, serial);
    sync_clock_to_slave(&is->extclk, &is->vidclk);
}

/* called to display each frame */
void Qffplayer::video_refresh(void *opaque, double *remaining_time)
{
    PlayerCore *is = (PlayerCore *)opaque;
    double time;

    Frame *sp, *sp2;

    double rdftspeed = 0.02;

    if (!is->paused && get_master_sync_type(is) == AV_SYNC_EXTERNAL_CLOCK && is->realtime)
        check_external_clock_speed(is);

    if (is->video_st) {
    retry:
        if (frame_queue_nb_remaining(&is->pictq) == 0) {
            // nothing to do, no picture to display in the queue
        }
        else {

            double last_duration, duration, delay;
            Frame *vp, *lastvp;

            /* dequeue the picture */
            lastvp = frame_queue_peek_last(&is->pictq);
            vp = frame_queue_peek(&is->pictq);

            if (vp->serial != is->videoq.serial) {
                frame_queue_next(&is->pictq);
                goto retry;
            }

            if (lastvp->serial != vp->serial)
                is->frame_timer = av_gettime_relative() / 1000000.0;

            if (is->paused)
                goto display;

            /* compute nominal last_duration */
            last_duration = vp_duration(is, lastvp, vp);
            delay = compute_target_delay(last_duration, is);

            time = av_gettime_relative() / 1000000.0;
            //qDebug()<< "time:" << QString::number(time, 'f', 6) <<"is->frame_timer:"<<QString::number(is->frame_timer,'f', 6)<<"delay:"<<delay<< endl;
            if (time < is->frame_timer + (delay/m_CurStream->play_speed)) {  // 重要：控制图片显示的时间
                *remaining_time = FFMIN(is->frame_timer + delay - time, *remaining_time);

                goto display;
            }

            is->frame_timer += (delay/m_CurStream->play_speed);
            if (delay > 0 && time - is->frame_timer > AV_SYNC_THRESHOLD_MAX)
                is->frame_timer = time;

            SDL_LockMutex(is->pictq.mutex);
            if (!std::isnan(vp->pts))
                update_video_pts(is, vp->pts, vp->pos, vp->serial);
            SDL_UnlockMutex(is->pictq.mutex);

            if (frame_queue_nb_remaining(&is->pictq) > 1) {
                Frame *nextvp = frame_queue_peek_next(&is->pictq);
                duration = vp_duration(is, vp, nextvp);
                if (!is->step && (framedrop>0 || (framedrop > 0 && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) && time > is->frame_timer + duration) {
                    is->frame_drops_late++;
                    frame_queue_next(&is->pictq);
                    goto retry;
                }
            }
            frame_queue_next(&is->pictq);
            is->force_refresh = 1;

            if (is->step && !is->paused)
                stream_toggle_pause(is);
        }
    display:
        /* display picture */
        //time = av_gettime_relative() / 1000000.0;
        //qDebug()<< "time:" << QString::number(time, 'f', 6) <<"force_refresh:"<<is->force_refresh<< endl;
        if (is->force_refresh && is->pictq.rindex_shown){
            video_image_display(is);
            double p =get_master_clock(is);
            if(prevPts == -1 || abs(p-prevPts) > 1){
                emit sigPlayerCb(3,QString::number(p), 0, 0);
                prevPts = (int)p;
            }
        }
    }
    is->force_refresh = 0;


    // qDebug() << "end video_refresh:" << av_gettime()/1000<< endl;
}

int Qffplayer::queue_picture(PlayerCore *is, AVFrame *src_frame, double pts, double duration, int64_t pos, int serial)
{
    Frame *vp;
    if (!(vp = frame_queue_peek_writable(&is->pictq)))
        return -1;
    vp->sar = src_frame->sample_aspect_ratio;
    vp->uploaded = 0;

    vp->width = src_frame->width;
    vp->height = src_frame->height;
    vp->format = src_frame->format;

    vp->pts = pts;
    vp->duration = duration;
    vp->pos = pos;
    vp->serial = serial;

    av_frame_move_ref(vp->frame, src_frame);
    frame_queue_push(&is->pictq);
    return 0;
}

//从视频队列中获取数据，并解码数据，得到可显示的视频帧
int Qffplayer::get_video_frame(PlayerCore *is, AVFrame *frame)
{
    int got_picture;
    if ((got_picture = decoder_decode_frame(&is->viddec, frame, NULL)) < 0){
        qDebug() << "decoder error:" << av_gettime()/1000<< endl;
        return -1;
    }
    if (got_picture) {
        double dpts = NAN;

        if (frame->pts != AV_NOPTS_VALUE)
            dpts = av_q2d(is->video_st->time_base) * frame->pts;

        frame->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, frame);

        if (framedrop > 0 || (framedrop>0 && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) {
            if (frame->pts != AV_NOPTS_VALUE) {
                double diff = dpts - get_master_clock(is);
                if (!isnan(diff) && fabs(diff) < AV_NOSYNC_THRESHOLD &&
                    diff - is->frame_last_filter_delay < 0 &&
                    is->viddec.pkt_serial == is->vidclk.serial &&
                    is->videoq.nb_packets) {
                    is->frame_drops_early++;
                    av_frame_unref(frame);
                    got_picture = 0;
                }
            }
        }
    }

    return got_picture;
}


int Qffplayer::audio_thread(void *arg)
{
    PlayerCore *is = (PlayerCore *)arg;
    AVFrame *frame = av_frame_alloc();
    Frame *af;

    int got_frame = 0;
    AVRational tb;
    int ret = 0;

    if (!frame)
        return AVERROR(ENOMEM);

    do {
        AVPacket* pkt = NULL;
        if ((got_frame = decoder_decode_frame(&is->auddec, frame, NULL, &pkt)) < 0)
            goto the_end;

        if (got_frame) {
            tb = { 1, frame->sample_rate };

            if (!(af = frame_queue_peek_writable(&is->sampq)))
                goto the_end;

            af->pts = (frame->pts == AV_NOPTS_VALUE) ? NAN : frame->pts * av_q2d(tb);
            af->pos = frame->pkt_pos;
            af->serial = is->auddec.pkt_serial;
            af->duration = av_q2d({ frame->nb_samples, frame->sample_rate });
            af->pkt = pkt;
            av_frame_move_ref(af->frame, frame);
            frame_queue_push(&is->sampq);

        }
    } while (ret >= 0 || ret == AVERROR(EAGAIN) || ret == AVERROR_EOF);
the_end:

    av_frame_free(&frame);
    return ret;
}

//视频解码线程
int Qffplayer::video_thread(void *arg)
{
    PlayerCore *is = (PlayerCore *)arg;
    AVFrame *frame = av_frame_alloc();
    double pts;
    double duration;
    int ret;
    AVRational tb = is->video_st->time_base;
    AVRational frame_rate = av_guess_frame_rate(is->ic, is->video_st, NULL);

    if (!frame) 
    {
        return AVERROR(ENOMEM);
    }

    //循环从队列中获取视频帧
    for (;;) {
        ret = get_video_frame(is, frame);
        if (ret < 0)
            goto the_end;
        if (!ret)
            continue;

        duration = (frame_rate.num && frame_rate.den ? av_q2d({ frame_rate.den, frame_rate.num }) : 0);
        pts = (frame->pts == AV_NOPTS_VALUE) ? NAN : frame->pts * av_q2d(tb);
        ret = queue_picture(is, frame, pts, duration, frame->pkt_pos, is->viddec.pkt_serial);
        av_frame_unref(frame);

        if (ret < 0)
            goto the_end;
    }
the_end:

    av_frame_free(&frame);
    return 0;
}

/* copy samples for viewing in editor window */
void Qffplayer::update_sample_display(PlayerCore *is, short *samples, int samples_size)
{
    int size, len;

    size = samples_size / sizeof(short);
    while (size > 0) {
        len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
        if (len > size)
            len = size;
        memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
        samples += len;
        is->sample_array_index += len;
        if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
            is->sample_array_index = 0;
        size -= len;
    }
}

/* return the wanted number of samples to get better sync if sync_type is video
* or external master clock */
int Qffplayer::synchronize_audio(PlayerCore *is, int nb_samples)
{
    int wanted_nb_samples = nb_samples;

    /* if not master, then we try to remove or add samples to correct the clock */
    if (get_master_sync_type(is) != AV_SYNC_AUDIO_MASTER) {
        double diff, avg_diff;
        int min_nb_samples, max_nb_samples;

        diff = get_clock(&is->audclk) - get_master_clock(is);

        if (!std::isnan(diff) && fabs(diff) < AV_NOSYNC_THRESHOLD) {
            is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
            if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
                /* not enough measures to have a correct estimate */
                is->audio_diff_avg_count++;
            }
            else {
                /* estimate the A-V difference */
                avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);

                if (fabs(avg_diff) >= is->audio_diff_threshold) {
                    wanted_nb_samples = nb_samples + (int)(diff * is->audio_src.freq);
                    min_nb_samples = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100));
                    max_nb_samples = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100));
                    wanted_nb_samples = av_clip(wanted_nb_samples, min_nb_samples, max_nb_samples);
                }
                av_log(NULL, AV_LOG_TRACE, "diff=%f adiff=%f sample_diff=%d apts=%0.3f %f\n",
                       diff, avg_diff, wanted_nb_samples - nb_samples,
                       is->audio_clock, is->audio_diff_threshold);
            }
        }
        else {
            /* too big difference : may be initial PTS errors, so
            reset A-V filter */
            is->audio_diff_avg_count = 0;
            is->audio_diff_cum = 0;
        }
    }

    return wanted_nb_samples;
}

/**
* Decode one audio frame and return its uncompressed size.
*
* The processed audio frame is decoded, converted if required, and
* stored in is->audio_buf, with size in bytes given by the return
* value.
*/
int Qffplayer::audio_decode_frame(PlayerCore *is)
{
    static int c = 0;
    int data_size, resampled_data_size;
    av_unused double audio_clock0;
    int wanted_nb_samples;
    Frame* af;

    if (is->paused)
        return -1;

    do {
#if defined(_WIN32)
        while (frame_queue_nb_remaining(&is->sampq) == 0) {
            if ((av_gettime_relative() - audio_callback_time) > 1000000LL * is->audio_hw_buf_size / is->audio_tgt.bytes_per_sec / 2)
                return -1;
            av_usleep(1000);
        }
#endif
        if (!(af = frame_queue_peek_readable(&is->sampq)))
            return -1;
        frame_queue_next(&is->sampq);
    } while (af->serial != is->audioq.serial);

    if(is->out_ctx && is->audio_encoder && af->pkt != NULL){

        if(is->out_audio_pts == -1)
            is->out_audio_pts = 0;

        af->pkt->dts = af->pkt->pts = (is->out_audio_pts+is->audio_pts_gap);
        is->out_audio_pts += is->audio_pts_gap;

        //qDebug() << "audio writePacket:"<< is->out_ctx->streams[is->audio_stream]->time_base.den << endl;
        //qDebug() << "audio frameszie:"<< af->pkt->pts << endl;
        //qDebug() << "audio is->out_audio_pts"<< is->out_audio_pts << endl;
        writePacket(af->pkt, this->m_CurStream->out_ctx, this->m_CurStream->out_a_index);
        av_packet_unref(af->pkt);
        af->pkt = NULL;
    }else{
        is->out_audio_pts = -1;
    }

    data_size = av_samples_get_buffer_size(NULL, af->frame->ch_layout.nb_channels,
                                           af->frame->nb_samples,
                                           (AVSampleFormat)af->frame->format, 1);

    wanted_nb_samples = synchronize_audio(is, af->frame->nb_samples);

    if (af->frame->format != is->audio_src.fmt ||
        av_channel_layout_compare(&af->frame->ch_layout, &is->audio_src.ch_layout) ||
        af->frame->sample_rate != is->audio_src.freq ||
        (wanted_nb_samples != af->frame->nb_samples && !is->swr_ctx)) {
        swr_free(&is->swr_ctx);
        swr_alloc_set_opts2(&is->swr_ctx,
                            &is->audio_tgt.ch_layout, is->audio_tgt.fmt, is->audio_tgt.freq,
                            &af->frame->ch_layout, (AVSampleFormat)af->frame->format, af->frame->sample_rate,
                            0, NULL);
        if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
            av_log(NULL, AV_LOG_ERROR,
                   "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
                   af->frame->sample_rate, av_get_sample_fmt_name((AVSampleFormat)af->frame->format), af->frame->ch_layout.nb_channels,
                   is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.ch_layout.nb_channels);
            swr_free(&is->swr_ctx);
            return -1;
        }
        if (av_channel_layout_copy(&is->audio_src.ch_layout, &af->frame->ch_layout) < 0)
            return -1;
        is->audio_src.freq = af->frame->sample_rate;
        is->audio_src.fmt = (AVSampleFormat)af->frame->format;
    }

    if (is->swr_ctx) {
        const uint8_t** in = (const uint8_t**)af->frame->extended_data;
        uint8_t** out = &is->audio_buf1;
        int out_count = (int64_t)wanted_nb_samples * is->audio_tgt.freq / af->frame->sample_rate + 256;
        int out_size = av_samples_get_buffer_size(NULL, is->audio_tgt.ch_layout.nb_channels, out_count, is->audio_tgt.fmt, 0);
        int len2;
        if (out_size < 0) {
            av_log(NULL, AV_LOG_ERROR, "av_samples_get_buffer_size() failed\n");
            return -1;
        }
        if (wanted_nb_samples != af->frame->nb_samples) {
            if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - af->frame->nb_samples) * is->audio_tgt.freq / af->frame->sample_rate,
                                     wanted_nb_samples * is->audio_tgt.freq / af->frame->sample_rate) < 0) {
                av_log(NULL, AV_LOG_ERROR, "swr_set_compensation() failed\n");
                return -1;
            }
        }
        av_fast_malloc(&is->audio_buf1, &is->audio_buf1_size, out_size);
        if (!is->audio_buf1)
            return AVERROR(ENOMEM);
        len2 = swr_convert(is->swr_ctx, out, out_count, in, af->frame->nb_samples);
        if (len2 < 0) {
            av_log(NULL, AV_LOG_ERROR, "swr_convert() failed\n");
            return -1;
        }
        if (len2 == out_count) {
            av_log(NULL, AV_LOG_WARNING, "audio buffer is probably too small\n");
            if (swr_init(is->swr_ctx) < 0)
                swr_free(&is->swr_ctx);
        }
        is->audio_buf = is->audio_buf1;
        resampled_data_size = len2 * is->audio_tgt.ch_layout.nb_channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
    }
    else {
        is->audio_buf = af->frame->data[0];
        resampled_data_size = data_size;
    }

    audio_clock0 = is->audio_clock;
    /* update the audio clock with the pts */
    if (!isnan(af->pts))
        is->audio_clock = af->pts + (double)af->frame->nb_samples / af->frame->sample_rate;
    else
        is->audio_clock = NAN;
    is->audio_clock_serial = af->serial;
#ifdef DEBUG
    {
        static double last_clock;
        printf("audio: delay=%0.3f clock=%0.3f clock0=%0.3f\n",
               is->audio_clock - last_clock,
               is->audio_clock, audio_clock0);
        last_clock = is->audio_clock;
    }
#endif
    return resampled_data_size;
}

/* prepare a new audio buffer */
void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
{
    Qffplayer *pVideoCtl = (Qffplayer*)opaque;
    if(pVideoCtl && pVideoCtl->m_bPlayLoop == false)
    {
        pVideoCtl->audio_playing = false;
        qDebug() << "close audio" << endl;
        return ;
    }

    pVideoCtl->audio_playing = true;
    PlayerCore *is = (PlayerCore *)pVideoCtl->m_CurStream;
    if(is == NULL){
        pVideoCtl->audio_playing = false;
        return ;
    }
    int audio_size, len1;

    audio_callback_time = av_gettime_relative();

    while (len > 0) {

        if (is->audio_buf_index >= is->audio_buf_size) {

            audio_size = pVideoCtl->audio_decode_frame(is);
            if (audio_size < 0) {
                /* if error, just output silence */
                is->audio_buf = NULL;
                is->audio_buf_size = SDL_AUDIO_MIN_BUFFER_SIZE / is->audio_tgt.frame_size * is->audio_tgt.frame_size;
            }
            else {
                is->audio_buf_size = audio_size;
            }
            is->audio_buf_index = 0;
        }
        len1 = is->audio_buf_size - is->audio_buf_index;
        if (len1 > len)
            len1 = len;
        if (is->audio_buf && is->audio_volume != 0 /*&& is->audio_volume == SDL_MIX_MAXVOLUME*/)
            memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
        else {
            memset(stream, 0, len1);
            if (is->audio_buf){

                SDL_MixAudio(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1, is->audio_volume);
            }
        }
        len -= len1;
        stream += len1;
        is->audio_buf_index += len1;
    }
    is->audio_write_buf_size = is->audio_buf_size - is->audio_buf_index;
    /* Let's assume the audio driver that is used by SDL has two periods. */
    if (!std::isnan(is->audio_clock)) {
        pVideoCtl->set_clock_at(&is->audclk, is->audio_clock - (double)(2 * is->audio_hw_buf_size + is->audio_write_buf_size) / is->audio_tgt.bytes_per_sec, is->audio_clock_serial, audio_callback_time / 1000000.0);
        pVideoCtl->sync_clock_to_slave(&is->extclk, &is->audclk);
    }
}

int Qffplayer::audio_open(void* opaque, AVChannelLayout* wanted_channel_layout, int wanted_sample_rate, struct AudioParams* audio_hw_params)
{
    SDL_AudioSpec wanted_spec, spec;
    const char* env;
    static const int next_nb_channels[] = { 0, 0, 1, 6, 2, 6, 4, 6 };
    static const int next_sample_rates[] = { 0, 44100, 48000, 96000, 192000 };
    int next_sample_rate_idx = FF_ARRAY_ELEMS(next_sample_rates) - 1;
    int wanted_nb_channels = wanted_channel_layout->nb_channels;

    env = SDL_getenv("SDL_AUDIO_CHANNELS");
    if (env) {
        wanted_nb_channels = atoi(env);
        av_channel_layout_uninit(wanted_channel_layout);
        av_channel_layout_default(wanted_channel_layout, wanted_nb_channels);
    }
    if (wanted_channel_layout->order != AV_CHANNEL_ORDER_NATIVE) {
        av_channel_layout_uninit(wanted_channel_layout);
        av_channel_layout_default(wanted_channel_layout, wanted_nb_channels);
    }
    wanted_nb_channels = wanted_channel_layout->nb_channels;
    wanted_spec.channels = wanted_nb_channels;
    wanted_spec.freq = wanted_sample_rate;
    if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
        av_log(NULL, AV_LOG_ERROR, "Invalid sample rate or channel count!\n");
        return -1;
    }
    while (next_sample_rate_idx && next_sample_rates[next_sample_rate_idx] >= wanted_spec.freq)
        next_sample_rate_idx--;
    wanted_spec.format = AUDIO_S16SYS;
    wanted_spec.silence = 0;
    wanted_spec.samples = FFMAX(SDL_AUDIO_MIN_BUFFER_SIZE, 2 << av_log2(wanted_spec.freq / SDL_AUDIO_MAX_CALLBACKS_PER_SEC));
    wanted_spec.callback = sdl_audio_callback;
    wanted_spec.userdata = this;
    while (!(audio_dev = SDL_OpenAudioDevice(NULL, 0, &wanted_spec, &spec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_CHANNELS_CHANGE))) {
        av_log(NULL, AV_LOG_WARNING, "SDL_OpenAudio (%d channels, %d Hz): %s\n",
               wanted_spec.channels, wanted_spec.freq, SDL_GetError());
        wanted_spec.channels = next_nb_channels[FFMIN(7, wanted_spec.channels)];
        if (!wanted_spec.channels) {
            wanted_spec.freq = next_sample_rates[next_sample_rate_idx--];
            wanted_spec.channels = wanted_nb_channels;
            if (!wanted_spec.freq) {
                av_log(NULL, AV_LOG_ERROR,
                       "No more combinations to try, audio open failed\n");
                return -1;
            }
        }
        av_channel_layout_default(wanted_channel_layout, wanted_spec.channels);
    }
    if (spec.format != AUDIO_S16SYS) {
        av_log(NULL, AV_LOG_ERROR,
               "SDL advised audio format %d is not supported!\n", spec.format);
        return -1;
    }
    if (spec.channels != wanted_spec.channels) {
        av_channel_layout_uninit(wanted_channel_layout);
        av_channel_layout_default(wanted_channel_layout, spec.channels);
        if (wanted_channel_layout->order != AV_CHANNEL_ORDER_NATIVE) {
            av_log(NULL, AV_LOG_ERROR,
                   "SDL advised channel count %d is not supported!\n", spec.channels);
            return -1;
        }
    }

    audio_hw_params->fmt = AV_SAMPLE_FMT_S16;
    audio_hw_params->freq = spec.freq;
    if (av_channel_layout_copy(&audio_hw_params->ch_layout, wanted_channel_layout) < 0)
        return -1;
    audio_hw_params->frame_size = av_samples_get_buffer_size(NULL, audio_hw_params->ch_layout.nb_channels, 1, audio_hw_params->fmt, 1);
    audio_hw_params->bytes_per_sec = av_samples_get_buffer_size(NULL, audio_hw_params->ch_layout.nb_channels, audio_hw_params->freq, audio_hw_params->fmt, 1);
    if (audio_hw_params->bytes_per_sec <= 0 || audio_hw_params->frame_size <= 0) {
        av_log(NULL, AV_LOG_ERROR, "av_samples_get_buffer_size failed\n");
        return -1;
    }
    return spec.size;
}

/* open a given stream. Return 0 if OK */
//打开流
int Qffplayer::stream_component_open(PlayerCore *is, int stream_index)
{
    AVFormatContext* ic = is->ic;
    AVCodecContext* avctx;
    const AVCodec* codec;
    const char* forced_codec_name = NULL;
    AVDictionary* opts = NULL;
    const AVDictionaryEntry* t = NULL;
    int sample_rate;
    AVChannelLayout ch_layout;
    memset(&ch_layout, 0, sizeof(AVChannelLayout));
    int ret = 0;
    int stream_lowres = 0;

    if (stream_index < 0 || stream_index >= ic->nb_streams)
        return -1;

    avctx = avcodec_alloc_context3(NULL);
    if (!avctx)
        return AVERROR(ENOMEM);

    ret = avcodec_parameters_to_context(avctx, ic->streams[stream_index]->codecpar);
    if (ret < 0)
        goto fail;
    avctx->pkt_timebase = ic->streams[stream_index]->time_base;

    codec = avcodec_find_decoder(avctx->codec_id);

    switch (avctx->codec_type) {
    case AVMEDIA_TYPE_AUDIO: is->last_audio_stream = stream_index; break;
    case AVMEDIA_TYPE_VIDEO: is->last_video_stream = stream_index; break;
    }
    if (forced_codec_name)
        codec = avcodec_find_decoder_by_name(forced_codec_name);
    if (!codec) {
        if (forced_codec_name) av_log(NULL, AV_LOG_WARNING,
                   "No codec could be found with name '%s'\n", forced_codec_name);
        else                   av_log(NULL, AV_LOG_WARNING,
                   "No decoder could be found for codec %s\n", avcodec_get_name(avctx->codec_id));
        ret = AVERROR(EINVAL);
        goto fail;
    }

    avctx->codec_id = codec->id;
    if (stream_lowres > codec->max_lowres) {
        av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
               codec->max_lowres);
        stream_lowres = codec->max_lowres;
    }
    avctx->lowres = stream_lowres;

    //if (fast)
    //    avctx->flags2 |= AV_CODEC_FLAG2_FAST;

    opts = nullptr /*filter_codec_opts(codec_opts, avctx->codec_id, ic, ic->streams[stream_index], codec)*/;
    if (!av_dict_get(opts, "threads", NULL, 0))
        av_dict_set(&opts, "threads", "auto", 0);
    if (stream_lowres)
        av_dict_set_int(&opts, "lowres", stream_lowres, 0);
    if ((ret = avcodec_open2(avctx, codec, &opts)) < 0) {
        goto fail;
    }
    if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
        av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
        ret = AVERROR_OPTION_NOT_FOUND;
        goto fail;
    }

    is->eof = 0;
    ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
    switch (avctx->codec_type) {
    case AVMEDIA_TYPE_AUDIO:
#if CONFIG_AVFILTER
    {
        AVFilterContext* sink;

        is->audio_filter_src.freq = avctx->sample_rate;
        ret = av_channel_layout_copy(&is->audio_filter_src.ch_layout, &avctx->ch_layout);
        if (ret < 0)
            goto fail;
        is->audio_filter_src.fmt = avctx->sample_fmt;
        if ((ret = configure_audio_filters(is, afilters, 0)) < 0)
            goto fail;
        sink = is->out_audio_filter;
        sample_rate = av_buffersink_get_sample_rate(sink);
        ret = av_buffersink_get_ch_layout(sink, &ch_layout);
        if (ret < 0)
            goto fail;
    }
#else
        sample_rate = avctx->sample_rate;
        ret = av_channel_layout_copy(&ch_layout, &avctx->ch_layout);
        if (ret < 0)
            goto fail;
#endif

        /* prepare audio output */
        if ((ret = audio_open(this, &ch_layout, sample_rate, &is->audio_tgt)) < 0)
            goto fail;
        is->audio_hw_buf_size = ret;
        is->audio_src = is->audio_tgt;
        is->audio_buf_size = 0;
        is->audio_buf_index = 0;

        /* init averaging filter */
        is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
        is->audio_diff_avg_count = 0;
        /* since we do not have a precise anough audio FIFO fullness,
           we correct audio sync only if larger than this threshold */
        is->audio_diff_threshold = (double)(is->audio_hw_buf_size) / is->audio_tgt.bytes_per_sec;

        is->audio_stream = stream_index;
        is->audio_st = ic->streams[stream_index];

        if ((ret = decoder_init(&is->auddec, avctx, &is->audioq, is->continue_read_thread)) < 0)
            goto fail;
        if ((is->ic->iformat->flags & (AVFMT_NOBINSEARCH | AVFMT_NOGENSEARCH | AVFMT_NO_BYTE_SEEK)) && !is->ic->iformat->read_seek) {
            is->auddec.start_pts = is->audio_st->start_time;
            is->auddec.start_pts_tb = is->audio_st->time_base;
        }

        packet_queue_start(is->auddec.queue);
        is->auddec.decode_thread = std::thread(&Qffplayer::audio_thread, this, is);

        SDL_PauseAudioDevice(audio_dev, 0);

        break;
    case AVMEDIA_TYPE_VIDEO:
        is->video_stream = stream_index;
        is->video_st = ic->streams[stream_index];

        if ((ret = decoder_init(&is->viddec, avctx, &is->videoq, is->continue_read_thread)) < 0)
            goto fail;
        if(avctx->codec_type == AVMEDIA_TYPE_VIDEO /*&& avctx->pix_fmt != AV_PIX_FMT_RGB32*/)
        {
            is->out_buffer_video = (unsigned char *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_RGB24, avctx->width, avctx->height, 1));
            is->frame_rgb = av_frame_alloc();
            av_image_fill_arrays(is->frame_rgb->data,is->frame_rgb->linesize,is->out_buffer_video,AV_PIX_FMT_RGB24,avctx->width,avctx->height,1);
            is->rgb_convert_ctx = sws_getContext(avctx->width, avctx->height,avctx->pix_fmt,avctx->width,avctx->height,AV_PIX_FMT_RGB24,SWS_BICUBIC,NULL, NULL, NULL);
        }

        packet_queue_start(is->viddec.queue);
        is->viddec.decode_thread = std::thread(&Qffplayer::video_thread, this, is);
        is->queue_attachments_req = 1;

        break;
    default:
        break;
    }
    goto out;

fail:
    avcodec_free_context(&avctx);
out:
    av_channel_layout_uninit(&ch_layout);
    av_dict_free(&opts);

    return ret;
}

int decode_interrupt_cb(void *ctx)
{
    PlayerCore* is = (PlayerCore*)ctx;
    if(!is)
        return 1;
    return is->abort_request;
}

int Qffplayer::stream_has_enough_packets(AVStream* st, int stream_id, PacketQueue* queue) {
    return stream_id < 0 ||
           queue->abort_request ||
           (st->disposition & AV_DISPOSITION_ATTACHED_PIC) ||
           queue->nb_packets > MIN_FRAMES && (!queue->duration || av_q2d(st->time_base) * queue->duration > 1.0);
}

std::shared_ptr<MediaInfo> Qffplayer::get_mediainfo()
{

    std::shared_ptr<MediaInfo> mediaInfo = std::make_shared<MediaInfo>();
    if(this->m_CurStream && this->m_CurStream->video_st)
    {
        mediaInfo.get()->vinfo.codec_name = avcodec_get_name(this->m_CurStream->video_st->codecpar->codec_id);
        mediaInfo.get()->vinfo.width = this->m_CurStream->video_st->codecpar->width;
        mediaInfo.get()->vinfo.height = this->m_CurStream->video_st->codecpar->height;
        mediaInfo.get()->vinfo.framerate = av_q2d(this->m_CurStream->video_st->avg_frame_rate);
        mediaInfo.get()->vinfo.pix_format = (char*)av_get_pix_fmt_name((AVPixelFormat)this->m_CurStream->video_st->codecpar->format);
        mediaInfo.get()->vinfo.bit_rate = this->m_CurStream->video_st->codecpar->bit_rate;
    }

    if(this->m_CurStream && this->m_CurStream->audio_st)
    {
        mediaInfo.get()->ainfo.codec_name = avcodec_get_name(this->m_CurStream->audio_st->codecpar->codec_id);
        mediaInfo.get()->ainfo.sample_rate = this->m_CurStream->audio_st->codecpar->sample_rate;
        mediaInfo.get()->ainfo.channel = this->m_CurStream->audio_st->codecpar->channels;
        mediaInfo.get()->ainfo.sample_bits = this->m_CurStream->audio_st->codecpar->bits_per_coded_sample;
        mediaInfo.get()->ainfo.bit_rate = this->m_CurStream->audio_st->codecpar->bit_rate;
    }

    return mediaInfo;

}

int Qffplayer::is_realtime(AVFormatContext* s)
{
    qDebug() << "filename:"<< QString::fromStdString(this->m_CurStream->filename)<< endl;
    if (strstr(this->m_CurStream->filename.c_str(), "rtp:")
        || strstr(this->m_CurStream->filename.c_str(), "rtsp:")
        || strstr(this->m_CurStream->filename.c_str(), "rtmp:")
        || strstr(this->m_CurStream->filename.c_str(), "http:")
        || strstr(this->m_CurStream->filename.c_str(), "https:")
        )
        return 1;

    if (s->pb && (!strncmp(s->url, "rtp:", 4)
                  || !strncmp(s->url, "udp:", 4)
                  )
        )
        return 1;
    return 0;
}

int Qffplayer::open_encoder()
{
    int ret = -1;
    AVCodecContext* encoder_v = NULL;
    AVCodecContext* encoder_a = NULL;

    if(this->m_CurStream->video_st){

        if(this->m_CurStream->video_encoder)
            return -1;
        AVCodec* videoCodec = (AVCodec*)avcodec_find_encoder(AV_CODEC_ID_H264);
        encoder_v = avcodec_alloc_context3(videoCodec);
        encoder_v->width = this->m_CurStream->video_st->codecpar->width;
        encoder_v->height = this->m_CurStream->video_st->codecpar->height;
        encoder_v->time_base = av_inv_q(this->m_CurStream->video_st->r_frame_rate);
        encoder_v->framerate = this->m_CurStream->video_st->r_frame_rate;
        encoder_v->pix_fmt = AV_PIX_FMT_YUV420P;
        encoder_v->bit_rate = this->m_CurStream->video_st->codecpar->bit_rate;
        if(this->m_CurStream->video_st->codecpar->bit_rate == 0)
        {
            encoder_v->bit_rate = 1000*4000;
        }
        encoder_v->max_b_frames = 0;
        encoder_v->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
        encoder_v->codec_tag = 0;

        int ret = avcodec_open2(encoder_v, videoCodec, 0);
        if(ret < 0)
        {
            char __tmp[1024];
            av_strerror(ret, __tmp, sizeof(__tmp));
            qDebug() <<"ffmpeg error111:" <<  __tmp << "pix_fmt"<<encoder_v->pix_fmt<< endl;
            exit(1);
            return -1;
        }
    }

    if(this->m_CurStream->audio_st){
        if(this->m_CurStream->audio_encoder)
            return -1;
        AVCodec* audioCodec = (AVCodec*)avcodec_find_encoder(m_CurStream->audio_st->codecpar->codec_id);
        encoder_a = avcodec_alloc_context3(audioCodec);
        encoder_a->codec_id = m_CurStream->audio_st->codecpar->codec_id;
        encoder_a->codec = audioCodec;

        avcodec_parameters_to_context(encoder_a, m_CurStream->audio_st->codecpar);
        encoder_a->frame_size = m_CurStream->auddec.avctx->frame_size;
        encoder_a->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
        encoder_a->codec_tag = 0;
        ret = avcodec_open2(encoder_a, audioCodec, 0);
        if(ret < 0)
        {
            char __tmp[1024];
            av_strerror(ret, __tmp, sizeof(__tmp));
            qDebug() <<"ffmpeg error222:" <<  __tmp << endl;
            return -1;
        }
        //encoder_a->frame_size = m_CurStream->auddec.avctx->frame_size;
        this->m_CurStream->audio_encoder = encoder_a;
        //this->m_CurStream->audio_encoder ->frame_size = 2048;
        this->m_CurStream->video_encoder = encoder_v;
    }
    return 0;
}

int Qffplayer::open_output()
{
    if(open_encoder() < 0)
        return -1;
    this->m_CurStream->out_a_index = -1;
    this->m_CurStream->out_v_index = -1;

    AVDictionary* opts = NULL;
    AVFormatContext* ctx = NULL;
    int ret  = avformat_alloc_output_context2(&ctx, nullptr, NULL, "123.mp4");
    if(ret < 0)
    {
        av_log(NULL, AV_LOG_ERROR, "open output context failed\n");
        goto Error;
    }
    ret = avio_open2(&(ctx->pb), "123.mp4", AVIO_FLAG_WRITE,nullptr, nullptr);
    if(ret < 0)
    {
        av_log(NULL, AV_LOG_ERROR, "open avio failed");
        goto Error;
    }

    if(this->m_CurStream->video_st)
    {
        AVStream* stream = avformat_new_stream(ctx, nullptr);
        avcodec_parameters_from_context(stream->codecpar, this->m_CurStream->video_encoder);
        stream->avg_frame_rate = this->m_CurStream->video_st->avg_frame_rate;
        stream->r_frame_rate = this->m_CurStream->video_st->r_frame_rate;
        stream->codecpar->codec_tag = 0;
        this->m_CurStream->out_v_index = 0;
    }

    if(this->m_CurStream->audio_st)
    {
        AVStream* stream = avformat_new_stream(ctx, nullptr);;
        avcodec_parameters_copy(stream->codecpar, this->m_CurStream->audio_st->codecpar);
        stream->codecpar->codec_tag = 0;

        this->m_CurStream->out_a_index = 1;
    }

    av_dict_set(&opts, "movflags", "frag_keyframe+empty_moov", 0);
    ret = avformat_write_header(ctx, &opts);
    if(ret < 0)
    {
        av_log(NULL, AV_LOG_ERROR, "format write header failed");
        goto Error;
    }
    av_dump_format(ctx, 0, "123.mp4", 1);
    open_out_pts = -1;

    m_CurStream->audio_pts_gap = (float)(m_CurStream->auddec.avctx->frame_size)/m_CurStream->audio_st->codecpar->sample_rate;
    m_CurStream->audio_pts_gap = m_CurStream->audio_pts_gap /av_q2d(ctx->streams[m_CurStream->out_a_index]->time_base);

    m_CurStream->video_pts_gap = 1.0/av_q2d(this->m_CurStream->video_st->r_frame_rate);
    m_CurStream->video_pts_gap = m_CurStream->video_pts_gap /av_q2d(ctx->streams[m_CurStream->out_v_index]->time_base);

    m_CurStream->out_audio_pts = -1;
    m_CurStream->out_video_pts = -1;
    this->m_CurStream->out_ctx = ctx;
    return ret ;
Error:
    if(this->m_CurStream->out_ctx)
    {
        avformat_close_input(&this->m_CurStream->out_ctx);
        avformat_free_context(this->m_CurStream->out_ctx);
        this->m_CurStream->out_ctx = NULL;
    }
    return ret ;
}

void Qffplayer::ReadThread(PlayerCore *is)
{
    //PlayerCore *is = (PlayerCore *)arg;
    AVFormatContext* ic = NULL;
    int i, ret;
    int st_index[AVMEDIA_TYPE_NB];
    AVPacket* pkt = NULL;
    int64_t stream_start_time;
    int pkt_in_play_range = 0;
    AVDictionary* opts = nullptr;
    int orig_nb_streams = 0;
    SDL_mutex* wait_mutex = SDL_CreateMutex();
    int64_t pkt_ts;
    int infinite_buffer = -1;
    const char* wanted_stream_spec[AVMEDIA_TYPE_NB] = { 0 };

    if (!wait_mutex) {
        av_log(NULL, AV_LOG_FATAL, "SDL_CreateMutex(): %s\n", SDL_GetError());
        ret = AVERROR(ENOMEM);
        goto fail;
    }

    memset(st_index, -1, sizeof(st_index));
    is->eof = 0;


    pkt = av_packet_alloc();
    if (!pkt) {
        av_log(NULL, AV_LOG_FATAL, "Could not allocate packet.\n");
        ret = AVERROR(ENOMEM);
        goto fail;
    }

    //构建 处理封装格式 结构体
    ic = avformat_alloc_context();
    if (!ic) {
        av_log(NULL, AV_LOG_FATAL, "Could not allocate context.\n");
        ret = AVERROR(ENOMEM);
        goto fail;
    }
    ic->interrupt_callback.callback = decode_interrupt_cb;
    ic->interrupt_callback.opaque = is;

    if(strstr(is->filename.c_str(), "rtsp"))
    {
        av_dict_set(&opts, "rtsp_transport", "tcp", 0);
    }

    ret = avformat_open_input(&ic, is->filename.c_str(), nullptr, &opts);
    if (ret < 0) {
        goto fail;
    }

    is->ic = ic;
    av_format_inject_global_side_data(ic);


    orig_nb_streams = ic->nb_streams;
    //读取一部分视音频数据并且获得一些相关的信息
    ret = avformat_find_stream_info(ic, NULL);

    //     for (i = 0; i < orig_nb_streams; i++)
    //         av_dict_free(&opts[i]);
    //     av_freep(&opts);

    if (ret < 0) {
        av_log(NULL, AV_LOG_WARNING,
               "%s: could not find codec parameters\n", is->filename.c_str());
        goto fail;
    }

    if (ic->pb)
        ic->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use avio_feof() to test for the end

    is->max_frame_duration = (ic->iformat->flags & AVFMT_TS_DISCONT) ? 10.0 : 3600.0;

    is->realtime = is_realtime(ic);
    for (i = 0; i < ic->nb_streams; i++) {
        AVStream *st = ic->streams[i];
        enum AVMediaType type = st->codecpar->codec_type;
        st->discard = AVDISCARD_ALL;
        if (type >= 0 && wanted_stream_spec[type] && st_index[type] == -1)
            if (avformat_match_stream_specifier(ic, st, wanted_stream_spec[type]) > 0)
                st_index[type] = i;
    }
    for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
        if (wanted_stream_spec[(AVMediaType)i] && st_index[(AVMediaType)i] == -1) {
            av_log(NULL, AV_LOG_ERROR, "Stream specifier %s does not match any %s stream\n", wanted_stream_spec[(AVMediaType)i], av_get_media_type_string((AVMediaType)i));
            st_index[(AVMediaType)i] = INT_MAX;
        }
    }

    //获得视频、音频、字幕的流索引

    st_index[AVMEDIA_TYPE_VIDEO] =
        av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO,
                            st_index[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);

    st_index[AVMEDIA_TYPE_AUDIO] =
        av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO,
                            st_index[AVMEDIA_TYPE_AUDIO],
                            st_index[AVMEDIA_TYPE_VIDEO],
                            NULL, 0);

    st_index[AVMEDIA_TYPE_SUBTITLE] =
        av_find_best_stream(ic, AVMEDIA_TYPE_SUBTITLE,
                            st_index[AVMEDIA_TYPE_SUBTITLE],
                            (st_index[AVMEDIA_TYPE_AUDIO] >= 0 ?
                                                               st_index[AVMEDIA_TYPE_AUDIO] :
                                                               st_index[AVMEDIA_TYPE_VIDEO]),
                            NULL, 0);

    if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
        AVStream *st = ic->streams[st_index[AVMEDIA_TYPE_VIDEO]];
        AVCodecParameters *codecpar = st->codecpar;
        AVRational sar = av_guess_sample_aspect_ratio(ic, st, NULL);
    }

    /* open the streams */
    //打开音频流
    if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
        stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);
    }

    //打开视频流
    ret = -1;
    if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
        ret = stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);
    }

    if (is->video_stream < 0 && is->audio_stream < 0) {
        av_log(NULL, AV_LOG_FATAL, "Failed to open file '%s' or configure filtergraph\n",
               is->filename.c_str());
        ret = -1;
        goto fail;
    }

    if(is->realtime != 1)
        emit sigPlayerCb(2, QString::number(ic->duration / 1000000LL), ic->streams[st_index[AVMEDIA_TYPE_VIDEO]]->codecpar->width,
                         ic->streams[st_index[AVMEDIA_TYPE_VIDEO]]->codecpar->height);
    else
        emit sigPlayerCb(2, "0", ic->streams[st_index[AVMEDIA_TYPE_VIDEO]]->codecpar->width,
                         ic->streams[st_index[AVMEDIA_TYPE_VIDEO]]->codecpar->height);

    if (infinite_buffer < 0 && is->realtime)
        infinite_buffer = 1;

    //读取视频数据
    for (;;) {

        if (is->abort_request)
            break;

        if(need_open_output == true && m_CurStream->out_ctx == NULL){
            open_output();
        }

        if(need_open_output == false && m_CurStream->out_ctx != NULL){
            close_output();
        }

        if (is->paused != is->last_paused) {
            is->last_paused = is->paused;
            if (is->paused)
                is->read_pause_return = av_read_pause(ic);
            else
                av_read_play(ic);
        }

        if (is->seek_req) {
            int64_t seek_target = is->seek_pos;
            int64_t seek_min = is->seek_rel > 0 ? seek_target - is->seek_rel + 2 : INT64_MIN;
            int64_t seek_max = is->seek_rel < 0 ? seek_target - is->seek_rel - 2 : INT64_MAX;
            // FIXME the +-2 is due to rounding being not done in the correct direction in generation
            //      of the seek_pos/seek_rel variables

            ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR,
                       "%s: error while seeking\n", is->ic->url);
            }
            else {
                if (is->audio_stream >= 0)
                    packet_queue_flush(&is->audioq);
                if (is->video_stream >= 0)
                    packet_queue_flush(&is->videoq);
                if (is->seek_flags & AVSEEK_FLAG_BYTE) {
                    set_clock(&is->extclk, NAN, 0);
                }
                else {
                    set_clock(&is->extclk, seek_target / (double)AV_TIME_BASE, 0);
                }
            }
            is->seek_req = 0;
            is->queue_attachments_req = 1;
            is->eof = 0;
            if (is->paused)
                step_to_next_frame();
        }
        if (is->queue_attachments_req) {
            if (is->video_st && is->video_st->disposition & AV_DISPOSITION_ATTACHED_PIC) {
                if ((ret = av_packet_ref(pkt, &is->video_st->attached_pic)) < 0)
                    goto fail;
                packet_queue_put(&is->videoq, pkt);
                packet_queue_put_nullpacket(&is->videoq, pkt, is->video_stream);
            }
            is->queue_attachments_req = 0;
        }

        /* if the queue are full, no need to read more */
        if (infinite_buffer < 1 &&
            (is->audioq.size + is->videoq.size  > MAX_QUEUE_SIZE
             || (stream_has_enough_packets(is->audio_st, is->audio_stream, &is->audioq) &&
                 stream_has_enough_packets(is->video_st, is->video_stream, &is->videoq)
                 ))) {
            /* wait 10 ms */
            SDL_LockMutex(wait_mutex);
            SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
            SDL_UnlockMutex(wait_mutex);
            continue;
        }
        if (!is->paused &&
            (!is->audio_st || (is->auddec.finished == is->audioq.serial && frame_queue_nb_remaining(&is->sampq) == 0)) &&
            (!is->video_st || (is->viddec.finished == is->videoq.serial && frame_queue_nb_remaining(&is->pictq) == 0))) {

            //播放结束
            //emit SigStop();
            m_bPlayLoop = false;
            continue;
        }
        //按帧读取
        ret = av_read_frame(ic, pkt);
        if (ret < 0) {
            if ((ret == AVERROR_EOF || avio_feof(ic->pb)) && !is->eof) {
                if (is->video_stream >= 0)
                    packet_queue_put_nullpacket(&is->videoq, pkt, is->video_stream);
                if (is->audio_stream >= 0)
                    packet_queue_put_nullpacket(&is->audioq, pkt, is->audio_stream);
                //is->eof = 1;
                m_bPlayLoop = false;
                QThread::msleep(1);
                continue;
            }
            if (ic->pb && ic->pb->error)
                break;
            SDL_LockMutex(wait_mutex);
            SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
            SDL_UnlockMutex(wait_mutex);
            continue;
        }
        else {
            is->eof = 0;
        }

        /* check if packet is in play range specified by user, then queue, otherwise discard */
        stream_start_time = ic->streams[pkt->stream_index]->start_time;
        pkt_ts = pkt->pts == AV_NOPTS_VALUE ? pkt->dts : pkt->pts;
        pkt_in_play_range = AV_NOPTS_VALUE == AV_NOPTS_VALUE ||
                            (pkt_ts - (stream_start_time != AV_NOPTS_VALUE ? stream_start_time : 0)) *
                                        av_q2d(ic->streams[pkt->stream_index]->time_base) -
                                    (double)(0 != AV_NOPTS_VALUE ? 0 : 0) / 1000000
                                <= ((double)AV_NOPTS_VALUE / 1000000);
        //按数据帧的类型存放至对应队列
        if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {

            packet_queue_put(&is->audioq, pkt);
        }
        else if (pkt->stream_index == is->video_stream && pkt_in_play_range
                 && !(is->video_st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
            packet_queue_put(&is->videoq, pkt);
        }
        else {
            av_packet_unref(pkt);
        }
    }
fail:
    if(pkt)
        av_packet_unref(pkt);
    if (ic && !is->ic)
        avformat_close_input(&ic);

    SDL_DestroyMutex(wait_mutex);
    return ;
}

PlayerCore* Qffplayer::stream_open(const char *filename)
{
    PlayerCore *is;
    //构造视频状态类
    is = (PlayerCore *)av_mallocz(sizeof(PlayerCore));
    if (!is)
        return NULL;
    //视频文件名
    is->last_video_stream = is->video_stream = -1;
    is->last_audio_stream = is->audio_stream = -1;
    is->filename = filename;
    //指定输入格式
    is->ytop = 0;
    is->xleft = 0;

    /* start video display */
    //初始化视频帧队列
    if (frame_queue_init(&is->pictq, &is->videoq, VIDEO_PICTURE_QUEUE_SIZE, 1) < 0)
        goto fail;
    //初始化音频帧队列
    if (frame_queue_init(&is->sampq, &is->audioq, SAMPLE_QUEUE_SIZE, 1) < 0)
        goto fail;
    //初始化队列中的数据包
    if (packet_queue_init(&is->videoq) < 0 ||
        packet_queue_init(&is->audioq) < 0)
        goto fail;
    //构建 继续读取线程 信号量
    if (!(is->continue_read_thread = SDL_CreateCond())) {
        av_log(NULL, AV_LOG_FATAL, "SDL_CreateCond(): %s\n", SDL_GetError());
        goto fail;
    }
    //视频、音频 时钟
    init_clock(&is->vidclk, &is->videoq.serial);
    init_clock(&is->audclk, &is->audioq.serial);
    init_clock(&is->extclk, &is->extclk.serial);
    is->audio_clock_serial = -1;
    //音量
    //startup_volume = 1;
    if (startup_volume < 0)
        av_log(NULL, AV_LOG_WARNING, "-volume=%d < 0, setting to 0\n", startup_volume);
    if (startup_volume > 100)
        av_log(NULL, AV_LOG_WARNING, "-volume=%d > 100, setting to 100\n", startup_volume);
    startup_volume = av_clip(startup_volume, 0, 100);
    startup_volume = av_clip(SDL_MIX_MAXVOLUME * startup_volume / 100, 0, SDL_MIX_MAXVOLUME);
    is->audio_volume = startup_volume;

    is->av_sync_type = AV_SYNC_AUDIO_MASTER;

    //构建读取线程
    is->read_tid = std::thread(&Qffplayer::ReadThread, this, is);

    return is;

fail:
    stream_close(is);
    return NULL;
}

void Qffplayer::stream_cycle_channel(PlayerCore *is, int codec_type)
{
    AVFormatContext *ic = is->ic;
    int start_index, stream_index;
    int old_index;
    AVStream *st;
    AVProgram *p = NULL;
    int nb_streams = is->ic->nb_streams;

    if (codec_type == AVMEDIA_TYPE_VIDEO) {
        start_index = is->last_video_stream;
        old_index = is->video_stream;
    }
    else if (codec_type == AVMEDIA_TYPE_AUDIO) {
        start_index = is->last_audio_stream;
        old_index = is->audio_stream;
    }else{
        return ;
    }

    stream_index = start_index;

    if (codec_type != AVMEDIA_TYPE_VIDEO && is->video_stream != -1) {
        p = av_find_program_from_stream(ic, NULL, is->video_stream);
        if (p) {
            nb_streams = p->nb_stream_indexes;
            for (start_index = 0; start_index < nb_streams; start_index++)
                if (p->stream_index[start_index] == stream_index)
                    break;
            if (start_index == nb_streams)
                start_index = -1;
            stream_index = start_index;
        }
    }

    for (;;) {
        if (++stream_index >= nb_streams)
        {

            if (start_index == -1)
                return;
            stream_index = 0;
        }
        if (stream_index == start_index)
            return;
        st = is->ic->streams[p ? p->stream_index[stream_index] : stream_index];
        if (st->codecpar->codec_type == codec_type) {
            /* check that parameters are OK */
            switch (codec_type) {
            case AVMEDIA_TYPE_AUDIO:
                if (st->codecpar->sample_rate != 0 &&
                    st->codecpar->channels != 0)
                    goto the_end;
                break;
            case AVMEDIA_TYPE_VIDEO:
            case AVMEDIA_TYPE_SUBTITLE:
                goto the_end;
            default:
                break;
            }
        }
    }
the_end:
    if (p && stream_index != -1)
        stream_index = p->stream_index[stream_index];
    av_log(NULL, AV_LOG_INFO, "Switch %s stream from #%d to #%d\n",
           av_get_media_type_string((AVMediaType)codec_type),
           old_index,
           stream_index);

    stream_component_close(is, old_index);
    stream_component_open(is, stream_index);
}


void Qffplayer::refresh_loop_wait_event(PlayerCore *is) {

    double remaining_time = 0.0;
    if (!is->paused || is->force_refresh)
        video_refresh(is, &remaining_time);
    return ;
}

void Qffplayer::seek_chapter(PlayerCore *is, int incr)
{
    int64_t pos = get_master_clock(is) * AV_TIME_BASE;
    int i;

    if (!is->ic->nb_chapters)
        return;

    /* find the current chapter */
    for (i = 0; i < is->ic->nb_chapters; i++) {
        AVChapter *ch = is->ic->chapters[i];
        if (av_compare_ts(pos, /*AV_TIME_BASE_Q*/{ 1, AV_TIME_BASE }, ch->start, ch->time_base) < 0) {
            i--;
            break;
        }
    }

    i += incr;
    i = FFMAX(i, 0);
    if (i >= is->ic->nb_chapters)
        return;

    av_log(NULL, AV_LOG_VERBOSE, "Seeking to chapter %d.\n", i);
    stream_seek(is, av_rescale_q(is->ic->chapters[i]->start, is->ic->chapters[i]->time_base,
                                 /*AV_TIME_BASE_Q*/{ 1, AV_TIME_BASE }), 0);
}

//播放控制循环
void Qffplayer::LoopThread(PlayerCore *cur_stream)
{
    m_bPlayLoop = true;

    while (m_bPlayLoop)
    {
        refresh_loop_wait_event(cur_stream);
        QThread::msleep(3);
    }

    do_exit(m_CurStream);
    //m_CurStream = nullptr;
}


int Qffplayer::setPlaySeek(int time)
{
    if (m_CurStream == nullptr || m_CurStream->realtime == 1)
    {
        return -1;
    }

    float d = (float)time/((float)m_CurStream->ic->duration / 1000000LL);

    int64_t ts = d * m_CurStream->ic->duration;
    if (m_CurStream->ic->start_time != AV_NOPTS_VALUE)
        ts += m_CurStream->ic->start_time;
    qDebug() << ts << endl;
    stream_seek(m_CurStream, ts, 0);
    return 0;
}

void Qffplayer::setPlayVolume(double dPercent)
{
    startup_volume = dPercent * SDL_MIX_MAXVOLUME;
    if (m_CurStream == nullptr)
    {
        return;
    }
    m_CurStream->audio_volume = startup_volume;
}

void Qffplayer::OnSeekForward()
{
    if (m_CurStream == nullptr)
    {
        return;
    }
    double incr = 5.0;
    double pos = get_master_clock(m_CurStream);
    if (std::isnan(pos))
        pos = (double)m_CurStream->seek_pos / AV_TIME_BASE;
    pos += incr;
    if (m_CurStream->ic->start_time != AV_NOPTS_VALUE && pos < m_CurStream->ic->start_time / (double)AV_TIME_BASE)
        pos = m_CurStream->ic->start_time / (double)AV_TIME_BASE;
    stream_seek(m_CurStream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE));
}

void Qffplayer::OnSeekBack()
{
    if (m_CurStream == nullptr)
    {
        return;
    }
    double incr = -5.0;
    double pos = get_master_clock(m_CurStream);
    if (std::isnan(pos))
        pos = (double)m_CurStream->seek_pos / AV_TIME_BASE;
    pos += incr;
    if (m_CurStream->ic->start_time != AV_NOPTS_VALUE && pos < m_CurStream->ic->start_time / (double)AV_TIME_BASE)
        pos = m_CurStream->ic->start_time / (double)AV_TIME_BASE;
    stream_seek(m_CurStream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE));
}

void Qffplayer::UpdateVolume(int sign, double step)
{
    if (m_CurStream == nullptr)
    {
        return;
    }
    double volume_level = m_CurStream->audio_volume ? (20 * log(m_CurStream->audio_volume / (double)SDL_MIX_MAXVOLUME) / log(10)) : -1000.0;
    int new_volume = lrint(SDL_MIX_MAXVOLUME * pow(10.0, (volume_level + sign * step) / 20.0));
    m_CurStream->audio_volume = av_clip(m_CurStream->audio_volume == new_volume ? (m_CurStream->audio_volume + sign) : new_volume, 0, SDL_MIX_MAXVOLUME);
}

void Qffplayer::do_exit(PlayerCore* &is)
{
    while(this->audio_playing == true)
    {
        QThread::msleep(200);
    }
    qDebug() << "do exit" << endl;
    if (is)
    {
        stream_close(is);
        is = nullptr;
    }
    need_open_output = false;
    emit sigPlayerCb(1, "",0,0);
}

void Qffplayer::OnAddVolume()
{
    if (m_CurStream == nullptr)
    {
        return;
    }
    UpdateVolume(1, SDL_VOLUME_STEP);
}

void Qffplayer::OnSubVolume()
{
    if (m_CurStream == nullptr)
    {
        return;
    }
    UpdateVolume(-1, SDL_VOLUME_STEP);
}

int Qffplayer::setPause()
{
    if (m_CurStream == nullptr||m_CurStream->realtime == 1)
    {
        return -1;
    }

    toggle_pause(m_CurStream);

    return 0;
}

void Qffplayer::stopPlay()
{
    m_bPlayLoop = false;
}

bool is_sld_init = false;

Qffplayer::Qffplayer(QObject *parent) :
    QObject(parent),
    m_CurStream(nullptr),
    m_bPlayLoop(false),
    startup_volume(30)
{
    avdevice_register_all();
    //网络格式初始化
    avformat_network_init();
    Init();
}

bool Qffplayer::Init()
{
    if(is_sld_init == false){
        if (SDL_Init( SDL_INIT_AUDIO))
        {
            av_log(NULL, AV_LOG_FATAL, "Could not initialize SDL - %s\n", SDL_GetError());
            av_log(NULL, AV_LOG_FATAL, "(Did you set the DISPLAY variable?)\n");
            return false;
        }
        is_sld_init = true;
    }

    return true;
}

Qffplayer::~Qffplayer()
{
    avformat_network_deinit();

    SDL_Quit();

}

void Qffplayer::set_facedetect(bool isDetect)
{
    if(m_bPlayLoop == false)
        return ;

    this->faceDetect = isDetect;

    return ;
}

bool Qffplayer::get_facedetect()
{
    return this->faceDetect;
}

bool Qffplayer::StartPlay(QString strFileName)
{
    this->prevPts = -1;
    m_bPlayLoop = false;
    PlayerCore *is;

    char file_name[1024];
    memset(file_name, 0, 1024);
    sprintf(file_name, "%s", /*strFileName.toLocal8Bit().data()*/strFileName.toStdString().c_str());
    //打开流
    is = stream_open(file_name);
    if (!is) {
        emit sigPlayerCb(-1, "打开输入文件失败",1,1);
        av_log(NULL, AV_LOG_FATAL, "Failed to initialize PlayerCore!\n");
        do_exit(m_CurStream);
    }

    m_CurStream = is;
    this->m_CurStream->play_speed = 1;

    emit sigPlayerCb(0,"",1,1);
    //事件循环
    m_tPlayLoopThread = std::thread(&Qffplayer::LoopThread, this, is);
    m_tPlayLoopThread.detach();

    return true;
}
